package top.lcpsky.flashcards.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**   
 * @ClassName:  Snippet   
 * @Description:TODO(这里用一句话描述这个类的作用)   
 * @author: lcp
 * @date:   2020年3月30日 下午9:19:21   
 *     
 * @Copyright: 2020 www.ankept.com Inc. All rights reserved. 
 */
@Configuration  //声明这是一个注解类
@EnableSwagger2
public class SwaggerConfig {
	// 定义分隔符
    private static final String splitor = ";";
    @Bean
    public Docket customDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                 .apiInfo(apiInfo())
                .select()
                .apis(basePackage("top.lcpsky.flashcards.web"))
                .paths(PathSelectors.any()).build().pathMapping("/");
    }

    private ApiInfo apiInfo(){
        Contact contact = new Contact("flash-cards APIs",
                "http://www.lcpsky.com:8099",
                "248610401@qq.com");
        return new ApiInfoBuilder()
                .title("项目API接口")
                .description("接口描述")
                .contact(contact)
                .version("1.1.0")
                .build();
    }
    
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    @SuppressWarnings("deprecation")
	private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }


    /**
     * swagger2原始ui
     * http://localhost:8080/swagger-ui.html
     *
     * swagger-ui-layer访问ui
     * http://localhost:8080/docs.html
     */
}
